#!/usr/bin/env python
# Copyright (c) 2014 Eugene Frolov <efrolov@mirantis.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json

__author__ = "Evgeniy Frolov (e-mail: profisphantom@gmail.com)"
__version__ = "2.0.1"

from storage import Storage
import cgi

storage = Storage()
form = cgi.FieldStorage()

print "Content-Type: application/json\n"

if 'table' in form:
    table = form['table'].value
    if 'query' in form:
        query_filter = {}
        query_filter['query'] = form['query'].value
        query_filter['offset'] = int(form['start'].value)
        query_filter['limit'] = int(form['limit'].value)
    else:
        query_filter = None
    func = getattr(storage, table)
    print storage.json.convert_to_json(func(query_filter))
else:
    print json.dumps({'result': "Error. Table not found!"})
